package cn.ffcs.uec.outStaff.component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zkplus.databind.BindingListModelList;
import org.zkoss.zul.Div;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.outStaff.component.bean.UecOutStaffTitleListboxBean;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.staff.manager.UecTitleManager;
import cn.ffcs.uec.staff.manager.UecTrialManager;
import cn.ffcs.uec.staff.model.UecTitle;
import cn.ffcs.uec.staff.model.UecTrial;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.PageInfo;
import cn.ffcs.uom.common.zul.PubUtil;
import lombok.Getter;
import lombok.Setter;

/**
 * @Title:专业技术职务 CRUD插件
 * @Description:
 * @Company: FFCS
 * @Version 0.0.1 date:2018年5月27日
 * @since JDK1.6
 */
@Controller
@Scope("prototype")
public class UecOutStaffTitleListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -5811398149406451671L;
	/**
	 * 人员基本信息功能 查询出的实体对象
	 */
	private UecOutStaffInfo uecStaffInfo;
	/**
	 * 对应页面上的bean
	 */
	@Getter
	private UecOutStaffTitleListboxBean bean = new UecOutStaffTitleListboxBean();
	/**
	 * 专业技术职务实体
	 */
	private UecTitle uecTitle;
	/**
	 * 翻页查询条件实体
	 */
	private UecTitle titlePaging;

	private UecTitle approvalTitlePaging;
	/**
	 * 专业技术职务查询实体
	 */
	// private UecAss qryUecAss;

	private List<UecTitle> titleList = new ArrayList<UecTitle>();

	/**
	 * 是否为入职页面引用
	 */
	private boolean isOutStaffEntryExt = false;

	private UecTitleManager uecTitleManager = (UecTitleManager) ApplicationContextUtil
			.getBean("uecTitleManager");

	private UecTrialManager uecTrialManager = (UecTrialManager) ApplicationContextUtil
			.getBean("uecTrialManager");

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public UecOutStaffTitleListboxExt() {
		Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_STAFF_TITLE_EXT_LISTBOX_ZUL, this,
				null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

		this.addForward(UecOutStaffConstants.ON_UEC_OUT_STAFF_TITLE_QUERY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_TITLE_QUERY_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_TITLE_QUERY_OF_OUTSTAFF_ENTRY,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_TITLE_QUERY_OF_OUTSTAFF_RESPONSE);

		this.addForward(
				UecOutStaffConstants.ON_UEC_OUT_STAFF_TITLE_QUERY_OF_OUTSTAFF_ENTRY_VIEW,
				this,
				UecOutStaffConstants.ON_UEC_OUT_STAFF_TITLE_QUERY_OF_OUTSTAFF_VIEW_RESPONSE);

		this.addForward(UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_TITLE,
				this,
				UecOutStaffConstants.ON_CLEAN_UEC_OUT_STAFF_TITLE_RESPONSE);

	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 选择查询记录
	 * 
	 * @throws Exception
	 */
	public void onSelectUecTitleList() throws Exception {
		if (this.bean.getUecTitleListbox().getSelectedCount() > 0) {
			uecTitle = (UecTitle) bean.getUecTitleListbox().getSelectedItem()
					.getValue();
		}
	}

	/**
	 * 人员基本信息功能，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutStaffTitleQueryResponse(ForwardEvent event) {
		uecStaffInfo = (UecOutStaffInfo) event.getOrigin().getData();
		if (null != uecStaffInfo) {
            //设置操作按钮，非盟市主管不可操作按钮
            if(PermissionUtil.isNoMainOutStaff()) {
                this.setButtonValid(false, true, true, true);
            }else {
                this.setButtonValid(true, true, true, false);
            }
			uecTitle = new UecTitle();
			uecTitle.setStaffId(uecStaffInfo.getOutStaffId());
			uecTitle.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
			titlePaging = uecTitle;			
			this.onQueryUecTitle();
		}
	}

	/**
	 * 人员基本信息功能，抛出事件， 事件监听,来自入职页面
	 * 
	 * @param event
	 */
	public void onUecOutStaffTitleQueryOfOutStaffResponse(ForwardEvent event) {
		@SuppressWarnings("unchecked")
		Map<String, Object> map = (Map<String, Object>) event.getOrigin()
				.getData();
		if (null != map) {
			isOutStaffEntryExt = (Boolean) map.get("isOutStaffEntryExt");
			uecStaffInfo = (UecOutStaffInfo) map.get("uecOutStaffInfo");
			if (null != uecStaffInfo) {
				uecTitle = new UecTitle();
				uecTitle.setStaffId(uecStaffInfo.getOutStaffId());
				uecTitle.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
				this.setButtonValid(true, true, true, false);
				ListModel list = new BindingListModelList(titleList, true);
				this.bean.getUecTitleListbox().setModel(list);
				this.bean.getUecTitleListboxPaging().setTotalSize(1);

				uecTitle = null;
			}
		}
	}

	/**
	 * 入职审批中专业技术职务id，抛出事件， 事件监听
	 * 
	 * @param event
	 */
	public void onUecOutStaffTitleQueryOfOutStaffViewResponse(ForwardEvent event) {
		titleList.clear();
		approvalTitlePaging = new UecTitle();
		String titleIds = (String) event.getOrigin().getData();
		if (!StrUtil.isNullOrEmpty(titleIds)) {
			String[] titleIdArray = titleIds.split("-");
			if (!StrUtil.isNullOrEmpty(titleIdArray) && titleIdArray.length > 0) {
				for (String titleId : titleIdArray) {
					UecTitle uecTitle = UecTitle.newInstance();
					uecTitle.setTitleId(Long.parseLong(titleId));
					uecTitle = uecTitleManager.findUecTitleById(uecTitle);
					titleList.add(uecTitle);
				}
				onQueryUecTitle();
			}
		}

	}

	public void onCleanUecOutStaffTitleResponse(ForwardEvent event) {
		clearVariable();
		uecStaffInfo = null;
		ListboxUtils.clearListbox(this.bean.getUecTitleListbox());
		this.bean.getUecTitleListboxPaging().setTotalSize(1);
		this.setButtonValid(false, false, false, false);
	}

	/**
	 * 设置按钮
	 * 
	 * @param canAdd
	 * @param candel
	 */
	private void setButtonValid(boolean canView, boolean canAdd,
			boolean canEdit, boolean candel) {
		this.bean.getViewButton().setDisabled(!canView);
		this.bean.getAddButton().setDisabled(!canAdd);
		this.bean.getEditButton().setDisabled(!canEdit);
		this.bean.getDelButton().setDisabled(!candel);
	}

	/**
	 * 查询按钮
	 */
	public void onQueryUecTitle() {
		this.bean.getUecTitleListboxPaging().setActivePage(0);
		this.onQueryUecTitleList();
	}

	/**
	 * 重置按钮
	 */
	public void onResetUecTitle() {
		ListboxUtils.clearListbox(this.bean.getUecTitleListbox());
		this.bean.getUecTitleListboxPaging().setTotalSize(1);
	}

	/**
	 * 查看按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onViewUecTitle() throws Exception, InterruptedException {
		if (uecTitle != null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "view");
			map.put("uecTitle", uecTitle);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_TITLE_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						//
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要查看的记录", "提示信息");
		}
	}

	/**
	 * 新增按钮
	 * 
	 * @throws Exception
	 * @throws
	 */
	public void onAddUecTitle() throws Exception {
		if (null != uecStaffInfo) {
			if (!isOutStaffEntryExt) {
				boolean isOnTtrial = isOnTrial();
				if (!isOnTtrial) {
					return;
				}
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "add");
			map.put("uecOutStaffInfo", uecStaffInfo);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_TITLE_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						// 新增或修改完成后，列表从数据库更新
						uecTitle = (UecTitle) event.getData();
						titleList.add(uecTitle);
						if (!isOutStaffEntryExt) {
							onQueryUecTitleList();
						} else {
							ListModel list = new BindingListModelList(
									titleList, true);
							bean.getUecTitleListbox().setModel(list);
							bean.getUecTitleListboxPaging().setTotalSize(1);

							postTitleList();
						}

					}
				}
			});
		}
	}

	/**
	 * 编辑按钮
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void onEditUecTitle() throws Exception, InterruptedException {
		if (null != uecTitle) {
			if (!isOutStaffEntryExt) {
				boolean isOnTrial = isOnTrial();
				if (!isOnTrial) {
					return;
				}
			}

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "edit");
			map.put("uecTitle", uecTitle);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_TITLE_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						if (isOutStaffEntryExt) {
							titleList.remove(uecTitle);
						}
						uecTitle = (UecTitle) event.getData();
						// 新增或修改完成后，列表从数据库更新
						if (!isOutStaffEntryExt) {
							onQueryUecTitleList();
						} else {
							titleList.add(uecTitle);
							ListModel list = new BindingListModelList(
									titleList, true);
							bean.getUecTitleListbox().setModel(list);
							bean.getUecTitleListboxPaging().setTotalSize(1);

							postTitleList();
						}

					}
				}
			});
		} else {
			ZkUtil.showError("请选中要编辑的记录", "提示信息");
			return;
		}
	}

	/**
	 * 审批状态中修改
	 * 
	 * @throws InterruptedException
	 * @throws SuspendNotAllowedException
	 */
	public void onApprovalEditUecTitle() throws SuspendNotAllowedException,
			InterruptedException {
		if (null != uecTitle) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "approvalEdit");
			map.put("uecTitle", uecTitle);
			map.put("isOutStaffEntryExt", isOutStaffEntryExt);
			Window window = (Window) Executions.createComponents(
					UecOutStaffConstants.UEC_OUT_STAFF_TITLE_EDIT_ZUL, this,
					map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						uecTitle = (UecTitle) event.getData();
						// 新增或修改完成后，列表从数据库更新
						PageInfo pageInfo = uecTitleManager
								.queryPageInfoByUecTitleOnApproval(uecTitle,
										bean.getUecTitleListboxPaging()
												.getActivePage() + 1, bean
												.getUecTitleListboxPaging()
												.getPageSize());
						ListModel list = new BindingListModelList(pageInfo
								.getDataList(), true);
						bean.getUecTitleListbox().setModel(list);
						bean.getUecTitleListboxPaging().setTotalSize(1);

					}
				}
			});
		} else {
			ZkUtil.showError("请选中要修改的记录", "提示信息");
			return;
		}
	}

	/**
	 * 删除按钮
	 */
	public void onDelUecTitle() {
		if (uecTitle != null && null != uecTitle.getId()) {
			ZkUtil.showQuestion("确定要删除吗?", "提示信息", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Integer result = (Integer) event.getData();
					if (result == Messagebox.OK) {
						uecTitle.removeOnly();
						PubUtil.reDisplayListbox(bean.getUecTitleListbox(),
								uecTitle, "del");
						uecTitle = null;
					}
				}
			});
		} else {
			ZkUtil.showError("请选中要删除的记录", "提示信息");
			return;
		}
	}

	/**
	 * 抛给入职申请页面
	 */
	private void postTitleList() {
		Events.postEvent("onPostTitleListOfOutStaffEntry", this, titleList);
	}

	/**
	 * 翻页
	 */
	public void onUecTitleListboxPaging() {
		this.onQueryUecTitleList();
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecTitle = null;
		titleList.clear();
		titlePaging = null;
	}

	/**
	 * 查询
	 */
	public void onQueryUecTitleList() {
		// 翻页查看生效数据
		if (null != titlePaging) {
			PageInfo pageInfo = uecTitleManager.queryPageInfoByUecTitle(
					titlePaging, this.bean.getUecTitleListboxPaging()
							.getActivePage() + 1, this.bean
							.getUecTitleListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(pageInfo.getDataList(),
					true);
			this.bean.getUecTitleListbox().setModel(list);
			this.bean.getUecTitleListboxPaging().setTotalSize(
					pageInfo.getTotalCount());

		}
		// 翻页查看审批数据
		if (null != approvalTitlePaging) {
//			List<UecTitle> pageTitles = getCurrentPageList(titleList, bean
//					.getUecTitleListboxPaging().getActivePage() + 1, bean
//					.getUecTitleListboxPaging().getPageSize());
			ListModel list = new BindingListModelList(titleList, true);
			this.bean.getUecTitleListbox().setModel(list);
			this.bean.getUecTitleListboxPaging().setTotalSize(1);
		}
		// 入职 页添加记录后，不选择记录时 点击查看 编辑 按钮 弹出弹窗
		uecTitle = null;
	}

	/**
	 * 获取当前页list
	 * 
	 * @param list
	 * @param activePage
	 * @param pageSize
	 * @return
	 */
	public List<UecTitle> getCurrentPageList(List<UecTitle> list, int activePage,
			int pageSize) {
		int fromIndex = activePage * pageSize;
		int toIndex = fromIndex + pageSize;
		if (fromIndex >= list.size()) {
			return null;
		}
		if (toIndex >= list.size()) {
			return list.subList(fromIndex, list.size());
		}
		return list.subList(fromIndex, toIndex);

	}

	/**
	 * 判断是否入职
	 * 
	 * @return
	 */
	private boolean isOnTrial() {
		UecTrial qryUecTrial = UecTrial.newInstance();
		qryUecTrial.setStaffId(uecStaffInfo.getOutStaffId());
		qryUecTrial.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
		qryUecTrial = uecTrialManager.findUecTrial(qryUecTrial);
		if (null == qryUecTrial) {
			ZkUtil.showError("此人未入职,请先执行入职操作", "温馨提示");
			return false;
		}
		return true;
	}

}
